﻿/*
    desc:jQuery模拟盖章
    author:hyf
    date:2012-11-08
    */

$.fn.zSign = function (options) {
    var _s = $.extend({
           img: '',
         width: 120,
        height: 120,
        offsetX: 8,
        offsetY: 8,
     draggable: false,
      position: null,
      callBack: null
    }, options || {});

    var _parent = $(this).addClass('zsign');

    var range = {
        minX: 0,
        minY: 0,
        maxX: _parent.width() - _s.width /*- _s.offset */- 18,      //扣去2个padding=8px以及2个边框1px
        maxY: _parent.height() - _s.height /*- _s.offset */- 18
    };

    var _html = "";
    var sign;
    if( _s.position ){
        _html = "<div class='sign' style='height:" + _s.height + "px;width:" + _s.width + "px;top:" + _s.position.top + "px;left:" + _s.position.left + "px'><img src='" + _s.img + "' draggable='false'/>";
        sign = $(_html).appendTo(_parent);
        sign.addClass('ok');
    }else{
       _html = "<div class='sign' style='height:" + _s.height + "px;width:" + _s.width + "px;top:" + _s.offsetY + "px;left:" + _s.offsetX + "px'><img src='" + _s.img + "' draggable='false'/><button class='btn ok' >确定</button><button class='btn del' >删除</button></div>";
        sign = $(_html).appendTo(_parent);
    }

    $('.ok', sign).click(function () {
        /*确定盖章后移除鼠标事件*/
        sign.addClass('ok').off('mousedown').find('.btn').remove();
        $(".btn_sign").remove();//隐藏盖章按钮
        if(_s.callBack){
            _s.callBack();//加入回调
        }
    });

    $('.del', sign).click(function () {
        $(".btn_sign").attr("disabled",false);//启用盖章按钮
        //取消盖章
        sign.remove();
    });

    if(_s.draggable){
        //绑定移动事件
        sign.on('mousedown', function (e) {
            sign.data('x', e.clientX);
            sign.data('y', e.clientY);
            var position = sign.position();
            $(document).on('mousemove', function (e1) {
                var x = e1.clientX - sign.data('x') + position.left;
                var y = e1.clientY - sign.data('y') + position.top;
                x = x < range.minX ? range.minX : x;
                x = x > range.maxX ? range.maxX : x;
                y = y < range.minY ? range.minY : y;
                y = y > range.maxY ? range.maxY : y;

                sign.css({ left: x, top: y });
            }).on('mouseup', function () {
                $(this).off('mousemove').off('mouseup');
            });
        });
    }
};